package alp.starcode.sanping.framework.global;

import alp.starcode.common.base.constant.BaseResultDataConstant;
import alp.starcode.common.web.result.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应数据包装处理
 *
 * @description:
 * @author: Lw
 * @create: 2022-07-18 22:49
 **/
@Slf4j
@RestControllerAdvice(basePackages = "alp.starcode")
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断response响应数据类型是否是Result类型
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        boolean flag = true;
        if (methodParameter.getParameterType().isAssignableFrom(Result.class)) {
            // response是Result类型时不需要再包装
            flag = false;
        }
        return flag;
    }

    /**
     * 响应数据进行自动包装
     *
     * @param data       响应数据
     * @param returnType 返回类型
     * @param mediaType
     * @param aClass
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            // String类型不能直接包装
            if (returnType.getGenericParameterType().equals(String.class)) {
                ObjectMapper objectMapper = new ObjectMapper();
                // 将数据包装在ResultVo里后转换为json串进行返回
                return objectMapper.writeValueAsString(Result.success(data));
            } else if (returnType.getGenericParameterType().toString().equals("org.springframework.http.ResponseEntity<byte[]>")) {
                return data;
            }
            // 否则直接包装成ResultVo返回
            return Result.success(data);
        } catch (JsonProcessingException e) {
            return Result.error(e.getMessage(), BaseResultDataConstant.ERROR);
        }
    }
}
